package com.smart.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpCallUtil {
	private static final Logger log = LoggerFactory.getLogger(HttpCallUtil.class);
	private final static Logger errorLogger = LoggerFactory.getLogger("errorLogger");


	/**
	 * 发起http请求
	 * 
	 * @param HttpURL 请求链接
	 * @param method  方法名：post、get
	 * @param info    携带信息
	 * @return
	 */
	public static String CallHttp(String HttpURL, String method, String info) {
		HttpURLConnection httpurlconnection = null;
		String response = "";
		BufferedOutputStream out = null;
		BufferedReader in = null;
		InputStream is = null;
		try {
			// -------------------开始访问请求-------------------------------------------
			URL url = new URL(HttpURL);
			// 以post方式请求
			httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setRequestProperty("content-type", "text/html; charset=utf-8");
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setDoInput(true);
			httpurlconnection.setRequestMethod(method.toUpperCase());
			httpurlconnection.setConnectTimeout(5000);
			httpurlconnection.setReadTimeout(5000);
			if (info != null && !"".equals(info)) {
				info = URLEncoder.encode(info, "utf-8");
				/**
				 * 传输对象
				 */
				out = new BufferedOutputStream(httpurlconnection.getOutputStream());
				out.write(info.getBytes()); // 写入请求的字符串
				out.flush();
				out.close();

			}
			try {
				/**
				 * 当响应正常时，活的返回xml
				 */
				if (httpurlconnection.getResponseCode() == 200) {
					is = httpurlconnection.getInputStream();
					StringBuffer buffer = new StringBuffer();
					try {
						in = new BufferedReader(new InputStreamReader(is, "utf-8"));
						String line = "";
						while ((line = in.readLine()) != null) {
							buffer.append(line);
						}
					} catch (IOException e) {
						throw new Exception(e);
					}
					response = buffer.toString();
				}
			} catch (Exception e) {
				throw new Exception("获取HTTP服务返回对象出错！" + e);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpurlconnection != null) {
				httpurlconnection.disconnect();
			}
			try {
				if (in != null) {
					in.close();
					in = null;
				}
				if (is != null) {
					is.close();
					is = null;
				}
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (IOException e) {
			}

		}
		return response.toString();
	}

	private static RequestConfig requestConfig = null;

	static {
		// 设置请求和传输超时时间
		requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
	}

	/**
	 * post请求传输json参数
	 * 
	 * @param url  url地址
	 * @param json 参数
	 * @return
	 */
	public static JSONObject httpPost(String url, JSONObject jsonParam) {
		// post请求返回结果
		CloseableHttpClient httpClient = HttpClients.createDefault();
		JSONObject jsonResult = null;
		HttpPost httpPost = new HttpPost(url);
		// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		try {
			if (null != jsonParam) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				httpPost.setEntity(entity);
			}
			CloseableHttpResponse result = httpClient.execute(httpPost);
			// 请求发送成功，并得到响应
			if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String str = "";
				try {
					// 读取服务器返回过来的json字符串数据
					str = EntityUtils.toString(result.getEntity(), "utf-8");
					// 把json字符串转换成json对象
					jsonResult = JSONObject.parseObject(str);
				} catch (Exception e) {
					errorLogger.error("post请求提交失败:" + url, e);
				}
			}
		} catch (IOException e) {
			errorLogger.error("post请求提交失败:" + url, e);
		} finally {
			httpPost.releaseConnection();
		}
		return jsonResult;
	}
	public static JSONArray httpPostReturnArray(String url, JSONObject jsonParam) {
		// post请求返回结果
		CloseableHttpClient httpClient = HttpClients.createDefault();
		JSONArray jsonResult = null;
		HttpPost httpPost = new HttpPost(url);
		// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		try {
			if (null != jsonParam) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				httpPost.setEntity(entity);
			}
			CloseableHttpResponse result = httpClient.execute(httpPost);
			// 请求发送成功，并得到响应
			if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String str = "";
				try {
					// 读取服务器返回过来的json字符串数据
					str = EntityUtils.toString(result.getEntity(), "utf-8");
					// 把json字符串转换成json对象
					jsonResult = JSONArray.parseArray(str);
				} catch (Exception e) {
					errorLogger.error("post请求提交失败:" + url, e);
				}
			}
		} catch (IOException e) {
			errorLogger.error("post请求提交失败:" + url, e);
		} finally {
			httpPost.releaseConnection();
		}
		return jsonResult;
	}

	/**
	 * post请求传输String参数 例如：name=Jack&sex=1&type=2
	 * Content-type:application/x-www-form-urlencoded
	 * 
	 * @param url      url地址
	 * @param strParam 参数
	 * @return
	 */
	public static JSONObject httpPost(String url, String strParam) {
		// post请求返回结果
		CloseableHttpClient httpClient = HttpClients.createDefault();
		JSONObject jsonResult = null;
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		try {
			if (null != strParam) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(strParam, "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/x-www-form-urlencoded");
				httpPost.setEntity(entity);
			}
			CloseableHttpResponse result = httpClient.execute(httpPost);
			// 请求发送成功，并得到响应
			if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String str = "";
				try {
					// 读取服务器返回过来的json字符串数据
					str = EntityUtils.toString(result.getEntity(), "utf-8");
					// 把json字符串转换成json对象
					jsonResult = JSONObject.parseObject(str);
				} catch (Exception e) {
					errorLogger.error("post请求提交失败:" + url, e);
				}
			}
		} catch (IOException e) {
			errorLogger.error("post请求提交失败:" + url, e);
		} finally {
			httpPost.releaseConnection();
		}
		return jsonResult;
	}

	/**
	 * 发送get请求
	 * 
	 * @param url 路径
	 * @return
	 */
	public static JSONObject httpGet(String url) {
		// get请求返回结果
		JSONObject jsonResult = null;
		CloseableHttpClient client = HttpClients.createDefault();
		// 发送get请求
		HttpGet request = new HttpGet(url);
		request.setConfig(requestConfig);
		try {
			CloseableHttpResponse response = client.execute(request);

			// 请求发送成功，并得到响应
			HttpEntity entity = response.getEntity();
			String strResult = EntityUtils.toString(entity, "utf-8");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 读取服务器返回过来的json字符串数据
				// 把json字符串转换成json对象
				jsonResult = JSONObject.parseObject(strResult);
			} else {
				errorLogger.error("get请求提交失败:" + url);
				errorLogger.error("get请求提交失败:strResult=" + strResult);
			}
		} catch (IOException e) {
			errorLogger.error("get请求提交失败:" + url, e);
		} finally {
			request.releaseConnection();
		}
		return jsonResult;
	}
	public static JSONArray httpGetArray(String url) {
		// get请求返回结果
		JSONArray jsonResult = null;
		CloseableHttpClient client = HttpClients.createDefault();
		// 发送get请求
		HttpGet request = new HttpGet(url);
		request.setConfig(requestConfig);
		try {
			CloseableHttpResponse response = client.execute(request);
			
			// 请求发送成功，并得到响应
			HttpEntity entity = response.getEntity();
			String strResult = EntityUtils.toString(entity, "utf-8");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				jsonResult = JSONArray.parseArray(strResult);
			} else {
				errorLogger.error("get请求提交失败:" + url);
				errorLogger.error("get请求提交失败:strResult=" + strResult);
			}
		} catch (IOException e) {
			errorLogger.error("get请求提交失败:" + url, e);
		} finally {
			request.releaseConnection();
		}
		return jsonResult;
	}

	/**
	 * put请求传输json参数
	 * 
	 * @param url  url地址
	 * @param json 参数
	 * @return
	 */
	public static JSONObject httpPut(String url, JSONObject jsonParam) {
		// post请求返回结果
		CloseableHttpClient httpClient = HttpClients.createDefault();
		JSONObject jsonResult = null;
//    	HttpPost httpPost = new HttpPost(url);
		HttpPut httpPut = new HttpPut(url);
		// 设置请求和传输超时时间
		httpPut.setConfig(requestConfig);
		try {
			if (null != jsonParam) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				httpPut.setEntity(entity);
			}
			CloseableHttpResponse result = httpClient.execute(httpPut);
			int statusCode = result.getStatusLine().getStatusCode();
			// 请求发送成功，并得到响应
			if (statusCode == HttpStatus.SC_OK) {
				String str = "";
				try {
					// 读取服务器返回过来的json字符串数据
					str = EntityUtils.toString(result.getEntity(), "utf-8");
					// 把json字符串转换成json对象
					jsonResult = JSONObject.parseObject(str);
				} catch (Exception e) {
					errorLogger.error("put请求提交失败:" + url, e);
				}
			} else {
				log.info("put请求提交失败:statusCode=" + statusCode);
			}
		} catch (IOException e) {
			errorLogger.error("post请求提交失败:" + url, e);
		} finally {
			httpPut.releaseConnection();
		}
		return jsonResult;
	}
	/**
	 * put请求传输json参数
	 *
	 * @param url  url地址
	 * @param json 参数
	 * @return
	 */
	public static JSONObject httpPut(String url) {
		// post请求返回结果
		CloseableHttpClient httpClient = HttpClients.createDefault();
		JSONObject jsonResult = new JSONObject();
//    	HttpPost httpPost = new HttpPost(url);
		HttpPut httpPut = new HttpPut(url);
		// 设置请求和传输超时时间
		httpPut.setConfig(requestConfig);
		try {
			CloseableHttpResponse result = httpClient.execute(httpPut);
			int statusCode = result.getStatusLine().getStatusCode();
			// 请求发送成功，并得到响应
			jsonResult.put("code",statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				try {
					jsonResult.put("msg","提交成功");
				} catch (Exception e) {
					jsonResult.put("msg",e.getMessage());
					errorLogger.error("put请求提交失败:" + url, e);
				}
			} else {
				jsonResult.put("msg","提交失败");
				log.info("put请求提交失败:statusCode=" + statusCode);
			}
		} catch (IOException e) {
			errorLogger.error("post请求提交失败:" + url, e);
			jsonResult.put("msg",e.getMessage());

		} finally {
			httpPut.releaseConnection();
		}
		return jsonResult;
	}

}
